#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/8/30 11:53
# @Author : 闫峰
# @File    : sku_filter.py
import datetime

import requests

from common.setting import ensure_path_sep
from utils.mysqlUtils.db_pool import Database
import os
import threading
import time
from common.setting import ensure_path_sep
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database

current_path = os.path.abspath(__file__)
current_dir = os.path.dirname(current_path)
path_list = current_path.split("\\")
dis_path = "\\".join(path_list[-2:-1])


def remove_file(info_path):
    if os.path.exists(info_path):
        os.remove(info_path)
    else:
        print(f"{info_path} 不存在")


info_path = ensure_path_sep(f"\\logs\\info-{dis_path}{time.time()}")
error_path = ensure_path_sep(f"\\logs\\\error-{dis_path}{time.time()}.log")
warning_path = ensure_path_sep(f"\\logs\\warning-{dis_path}{time.time()}.log")
remove_file(info_path)
remove_file(error_path)
remove_file(warning_path)
INFO = LogHandler(info_path, level='info')
ERROR = LogHandler(error_path, level='error')
WARNING = LogHandler(warning_path, level='warning')


class Unpublish_service:
    db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")

    def unpublish_service(self, source_id):
        get_listings = """
        SELECT sku,source_id,source_sku,id
        FROM `test_zhcxkj_center_listing_comprehensive`.`t_walmart_listing` 
        WHERE id> %s
        and source_id =%s
        and status=1
        order by id 
        LIMIT 1000
        """
        id_offset = 0
        listing_list = []
        while True:
            listings = self.db.fetch_all_tuple(get_listings, (id_offset, source_id))
            print(f"id_offset= {id_offset}开始筛选")
            if len(listings):
                id_offset = listings[-1][-1]
                # 筛选出 禁售的listing
                no_sales_listings = list(filter(self.filter_no_sales, listings))
                # 筛选出 仿牌的listing
                product_property_listings = list(filter(self.filter_product_property, listings))
                # no_sales_listings_set = set(no_sales_listings)
                # product_property_listings_set = set(product_property_listings)
                # all_set = no_sales_listings_set | product_property_listings_set
                listing_list += (no_sales_listings + product_property_listings)
            else:
                WARNING.logger.warning(f"id_offset={id_offset}，没有数据了 退出")
                break
            print(f"当前listing_list{len(listing_list)}个")

        expect_set = set(map(lambda x: (x[1], x[0], x[2]), listing_list))
        INFO.logger.info(f"渠道={source_id},最终得到listing {len(expect_set)}个")
        # b = tuple(map(lambda x:x[2],a))

        # sql = """
        #    SELECT source_id,sku,source_sku
        #    FROM test_zhcxkj_center_strategy.t_walmart_execute_queue
        #    WHERE strategy_type=3 AND source_id=%s
        #    """
        # actual_list = self.db.fetch_all_tuple(sql, (source_id,))
        # actual_set = set(actual_list)
        # print(f"实际结果缺少的{expect_set - actual_set}")
        # print(f"实际结果比预期多的元素{actual_set - expect_set}")
        # print()

    def filter_no_sales(self, listing):
        sql = """
        SELECT id
        FROM test_zhcxkj_center_product.rb_product_no_sale
        WHERE platform_type=45
        AND sku=%s
        """
        res = self.db.fetch_all_tuple(sql, (listing[0],))
        if len(res):
            return True
        else:
            # ERROR.logger.error(f"{listing}被过滤 原因是 禁售")
            return False

    def filter_product_property(self, listing):
        # 侵权风险 非仿牌 = 1,仿牌 = 2,灰色产品 = 3
        sql = """
        SELECT id
        FROM test_zhcxkj_center_product.rb_product
        WHERE sku=%s
        AND product_property=2
        """
        res = self.db.fetch_all_tuple(sql, (listing[0],))
        if len(res):
            return True
        else:
            # ERROR.logger.error(f"{listing}被过滤 原因是 仿牌")
            return False


if __name__ == '__main__':
    # 16723
    Unpublish_service().unpublish_service(16130)
    # print(SkuFilter().get_platform_sales("16926140", 70, None))
    # orderSourceType_list = [2, 57]
    # sku = "10003056"
    # print(SkuFilter().first_time_filter("10001240"))
